package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.MyTheadLocal;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.OrdersDto;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private IOrderDetailService iOrderDetailService;

    @Autowired
    private IOrdersService iOrdersService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private IDishService iDishService;

    @Autowired
    private IDishFlavorService iDishFlavorService;

    @PostMapping("/submit")
    public R submitOrder(@RequestBody Orders orders){

        Long userId = MyTheadLocal.get();

        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCart = shoppingCartService.list(qw);
        if (shoppingCart == null || shoppingCart.size() == 0) {
            return R.error("当前购物车没有数据");
        }
        User user = userService.getById(userId);
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            return R.error("用户没有填写地址");
        }
        long orderWorkId = IdWorker.getId();
        BigDecimal amount = new BigDecimal(0);
        for (ShoppingCart cart : shoppingCart) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orderWorkId);
            BigDecimal price = cart.getAmount();
            BigDecimal number = new BigDecimal(cart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount = amount.add(orderDetail.getAmount());
            iOrderDetailService.save(orderDetail);
        }
        orders.setId(orderWorkId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(amount);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderWorkId));
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getPhone());

        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        iOrdersService.save(orders);
        LambdaQueryWrapper<ShoppingCart> remove = new LambdaQueryWrapper<>();
        remove.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(remove);

        return R.success(orders);
    }

    @GetMapping("/userPage")
    public R selectByPage(Integer page,Integer pageSize){

        Long userId = MyTheadLocal.get();

        IPage<Orders> page1 = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();

        IPage<Orders> page2 = iOrdersService.page(page1, qw);

        List<Orders> records = page2.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            ordersDtos.add(ordersDto);
        }

        long total = page2.getTotal();

        Map data = new HashMap();

        data.put("records",ordersDtos);

        data.put("total",total);

        return R.success(data);

    }


    @GetMapping("/page")
    //分页后端
    public R selectByPages(Integer page , Integer pageSize,String number,String beginTime,String endTime ){

        Long userId = MyTheadLocal.get();

        IPage<Orders> page1 = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();

        qw.eq(number != null,Orders::getNumber,number);

        qw.ge(beginTime != null,Orders::getOrderTime,beginTime);

        qw.le(endTime != null ,Orders::getCheckoutTime,endTime);

        IPage<Orders> page2 = iOrdersService.page(page1, qw);

        List<Orders> records = page2.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            ordersDtos.add(ordersDto);
        }

        long total = page2.getTotal();

        Map data = new HashMap();

        data.put("records",ordersDtos);

        data.put("total",total);


        return R.success(data);
    }

    @PutMapping
    //修改
    public R updateById(@RequestBody Orders orders){

        iOrdersService.updateById(orders);

        return R.success("成功");
    }



    @PostMapping("/again")
    //再来一单数据回显
    public R again(@RequestBody Orders orders){


        Long userid = MyTheadLocal.get();

        LambdaQueryWrapper<ShoppingCart> qwq = new LambdaQueryWrapper<>();

        qwq.eq(ShoppingCart::getUserId,userid);

        shoppingCartService.remove(qwq);


        Long ordersId = orders.getId();
        LambdaUpdateWrapper<OrderDetail> qw = new LambdaUpdateWrapper<>();
        qw.eq(ordersId != null,OrderDetail::getOrderId,ordersId);
        List<OrderDetail> orderDetailList = iOrderDetailService.list(qw);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            Long userId = iOrdersService.getById(orderDetail.getOrderId()).getUserId();
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setImage(orderDetail.getImage());
            //通过ID获得dish数据然后得到名字
            shoppingCart.setName(iDishService.getById(orderDetail.getDishId()).getName());
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());

            shoppingCarts.add(shoppingCart);
            shoppingCartService.save(shoppingCart);
        }


        for (ShoppingCart cart : shoppingCarts) {
            System.out.println(cart);
        }
        return R.success(shoppingCarts);
    }



}
